import json
import re

from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import render, redirect
from django.views import View
from django import http
# Create your views here.
from django_redis import get_redis_connection

from meiduo_mall.settings import dev
from oatuh.models import OAuthQQUser, OAuthSinaUser
from oatuh.utils import generate_sign_openid, decode_sign_openid
from users.models import User
from meiduo_mall.utils import sinaweibopy3


class OAuthQQLoginView(View):
    def get(self, request):
        state = request.GET.get("next", "/")
        oauth_qq = OAuthQQ(client_id=dev.QQ_CLIENT_ID,
                           client_secret=dev.QQ_CLIENT_SECRET,
                           redirect_uri=dev.QQ_REDIRECT_URI,
                           state=state)
        login_url = oauth_qq.get_qq_url()
        return http.JsonResponse({"login_url": login_url})


class OAuthUserView(View):
    def get(self, request):
        code = request.GET.get("code")
        state = request.GET.get("state", "/")

        if not code:
            return http.HttpResponseForbidden("code已丢失")

        oauth_qq = OAuthQQ(client_id=dev.QQ_CLIENT_ID,
                           client_secret=dev.QQ_CLIENT_SECRET,
                           redirect_uri=dev.QQ_REDIRECT_URI,
                           state=state)
        access_token = oauth_qq.get_access_token(code)
        openid = oauth_qq.get_open_id(access_token)

        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:
            sign_openid = generate_sign_openid(openid)
            return render(request, 'oauth_callback.html', context={"token": sign_openid})

        else:
            user = oauth_qq_user
            login(request, user)
            request.session.set_expiry(3600 * 24 * 2)


            response = redirect("/")
            response.set_cookie("username", user.username)
            return response



        # return http.HttpResponse("openid= %s" % openid)


    def post(self, request):
        sign_openid = request.POST.get("access_token")
        mobile = request.POST.get("mobile")
        pwd = request.POST.get("pwd")
        sms_code = request.POST.get("sms_code")


        if not all([sign_openid, mobile, pwd, sms_code]):
            return http.HttpResponse("信息填写不完整")

        openid = decode_sign_openid(sign_openid)
        if not openid:
            return http.HttpResponseForbidden("openid不存在")

        if not re.match(r"^1[3-9]\d{9}$", mobile):
            return http.HttpResponseForbidden("手机号格式有误")

        if not re.match(R"^[0-9a-zA-Z]\w{8,20}", pwd):
            return http.HttpResponseForbidden("密码格式有误")

        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s"%mobile)
        if not redis_sms_code:
            return http.HttpResponseForbidden("验证码已过期")

        if sms_code != redis_sms_code:
            return http.HttpResponseForbidden("验证码输入错误")


        # 判断是否存在美多用户，如果存在直接绑定，不存在的话直接创建用户再绑定

        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = User.objects.create_user(username=mobile, password=pwd, mobile=mobile)
            OAuthQQUser.objects.create(openid=openid, user=user)

            login(request, user)
            request.session.set_expiry(3600*24*2)

            response = redirect("/")
            response.set_cookie("username", user.username, max_age= 3600*24*2)
            return response

        else:
            if not user.check_password(pwd):
                return http.HttpResponseForbidden("密码错误")
            else:
                OAuthQQUser.objects.create(openid=openid, user=user)
                login(request, user)
                request.session.set_expiry(3600*24*2)

                response = redirect("/")
                response.set_cookie("username", user.username, max_age=3600 * 24 * 2)
                return response


# class WeiboLoginView(View):
#     def get(self, request):
#         state = request.GET.get("next", "/")
#         oauth_weibo = OAuthWeibo(client_id=dev.QQ_CLIENT_ID,
#                            client_secret=dev.QQ_CLIENT_SECRET,
#                            redirect_uri=dev.QQ_REDIRECT_URI,
#                            state=state)
#         login_url = oauth_qq.get_qq_url()
#
#         return http.JsonResponse({"login_url": login_url})


class WeiboLoginView(View):
    def get(self, request):
        client = sinaweibopy3.APIClient(app_key=settings.APP_KEY, app_secret=settings.APP_SECRET,
                                        redirect_uri=settings.REDIRECT_URL)
        login_url = client.get_authorize_url()

        return http.JsonResponse({"login_url": login_url})


class WeiboUserView(View):
    def get(self, request):
        code = request.GET.get("code")

        if not code:
            return http.HttpResponseForbidden("code已丢失")

        client = sinaweibopy3.APIClient(app_key=settings.APP_KEY, app_secret=settings.APP_SECRET,
                                        redirect_uri=settings.REDIRECT_URL)

        result = client.request_access_token(code)
        # access_token = result.access_token
        uid = result.uid

        try:
            Weibo_user = OAuthSinaUser.objects.get(uid=uid)

        except Exception as e:
            sign_uid = generate_sign_openid(uid)
            # return render(request, 'sina_callback.html', context={"access_token": sign_uid})

            context = {
                "access_token": sign_uid
            }

            return http.JsonResponse(context)

        else:
            user = Weibo_user.user
            login(request, user)
            request.session.set_expiry(3600 * 24 * 2)
            #
            #
            # response = redirect("/")
            # response.set_cookie("username", user.username)
            # return response
            sign_uid = generate_sign_openid(uid)
            context = {
                "user_id": user.id,
                "username": user.username,
                "token": sign_uid
            }
            return http.JsonResponse(context)

    def post(self, request):
        # sign_uid = request.POST.get("access_token")
        # mobile = request.POST.get("mobile")
        # pwd = request.POST.get("pwd")
        # sms_code = request.POST.get("sms_code")

        data = request.body.decode()
        data_dict = json.loads(data)

        sign_uid = data_dict.get('access_token')
        mobile = data_dict.get('mobile')
        pwd = data_dict.get('password')
        sms_code = data_dict.get('sms_code')
        state = data_dict.get('state', '/')

        if not all([sign_uid, mobile, pwd, sms_code]):
            return http.HttpResponse("信息填写不完整")

        uid = decode_sign_openid(sign_uid)
        if not uid:
            return http.HttpResponseForbidden("uid不存在")

        if not re.match(r"^1[3-9]\d{9}$", mobile):
            return http.HttpResponseForbidden("手机号格式有误")

        if not re.match(R"^[0-9a-zA-Z]\w{8,20}", pwd):
            return http.HttpResponseForbidden("密码格式有误")

        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s"%mobile)
        redis_sms_code = redis_sms_code.decode()
        if not redis_sms_code:
            return http.HttpResponseForbidden("验证码已过期")

        if sms_code != redis_sms_code:
            return http.HttpResponseForbidden("验证码输入错误")


        # 判断是否存在美多用户，如果存在直接绑定，不存在的话直接创建用户再绑定

        try:
            user = User.objects.get(mobile=mobile)

        except User.DoesNotExist:
            user = User.objects.create_user(username=mobile, password=pwd, mobile=mobile)
            OAuthSinaUser.objects.create(uid=uid, user=user)

            login(request, user)
            request.session.set_expiry(3600*24*2)

            context = {
                "token": uid,
                "user_id": user.id,
                "username": mobile
            }
            response = http.JsonResponse(context)
            response.set_cookie("username", user.username, max_age= 3600*24*2)
            return response

        else:
            if not user.check_password(pwd):
                return http.HttpResponseForbidden("密码错误")
            else:
                OAuthSinaUser.objects.create(uid=uid, user=user)
                login(request, user)
                request.session.set_expiry(3600*24*2)

                context= {
                "token": uid,
                "user_id": user.id,
                "username": mobile
                }
                response = http.JsonResponse(context)
                response.set_cookie("username", user.username, max_age=3600 * 24 * 2)
                return response


# class WeiboUserRegView(View):
#     def post(self, request):
#         sign_uid = request.POST.get("access_token")
#         mobile = request.POST.get("mobile")
#         pwd = request.POST.get("pwd")
#         sms_code = request.POST.get("sms_code")
#
#
#         if not all([sign_uid, mobile, pwd, sms_code]):
#             return http.HttpResponse("信息填写不完整")
#
#         uid = decode_sign_openid(sign_uid)
#         if not uid:
#             return http.HttpResponseForbidden("uid不存在")
#
#         if not re.match(r"^1[3-9]\d{9}$", mobile):
#             return http.HttpResponseForbidden("手机号格式有误")
#
#         if not re.match(R"^[0-9a-zA-Z]\w{8,20}", pwd):
#             return http.HttpResponseForbidden("密码格式有误")
#
#         redis_conn = get_redis_connection("code")
#         redis_sms_code = redis_conn.get("sms_code_%s"%mobile)
#         if not redis_sms_code:
#             return http.HttpResponseForbidden("验证码已过期")
#
#         if sms_code != redis_sms_code:
#             return http.HttpResponseForbidden("验证码输入错误")
#
#
#         # 判断是否存在美多用户，如果存在直接绑定，不存在的话直接创建用户再绑定
#
#         try:
#             user = User.objects.get(mobile=mobile)
#         except User.DoesNotExist:
#             user = User.objects.create_user(username=mobile, password=pwd, mobile=mobile)
#             OAuthSinaUser.objects.create(uid=uid, user=user)
#
#             login(request, user)
#             request.session.set_expiry(3600*24*2)
#
#             response = redirect("/")
#             response.set_cookie("username", user.username, max_age= 3600*24*2)
#             return response
#
#         else:
#             if not user.check_password(pwd):
#                 return http.HttpResponseForbidden("密码错误")
#             else:
#                 OAuthSinaUser.objects.create(uid=uid, user=user)
#                 login(request, user)
#                 request.session.set_expiry(3600*24*2)
#
#                 response = redirect("/")
#                 response.set_cookie("username", user.username, max_age=3600 * 24 * 2)
#                 return response


class WeiboUserFormView(View):
    def get(self, request):
        return render(request, "sina_callback.html")